/* lflWrite.c  -  lfWrite */

#include <xinu.h>

/*------------------------------------------------------------------------
 * lflWrite  --  write data to a previously opened local disk file
 *------------------------------------------------------------------------
 */
devcall	lflWrite (
	  struct dentry *devptr,	/* entry in device switch table */
	  char	*buff,			/* buffer holding data to write	*/
	  int32	count			/* number of bytes to write	*/
	)
{
	int32		i;		/* number of bytes written	*/
	int32	nxtbyte;		/* character or SYSERR/EOF	*/
	struct	lflcblk	*lfptr;		/* ptr to open file table entry	*/
	struct	ldentry	*ldptr;		/* ptr to file's entry in the	*/
	
	if (count < 0) {
		signal(lfptr->lfmutex);
		return SYSERR;
	}
		
	for (i=0; i<count; i++) {
		lfptr = &lfltab[devptr->dvminor];
		wait(lfptr->lfmutex);
		if (lfptr->lfstate != LF_USED) {
			signal(lfptr->lfmutex);
			nxtbyte = SYSERR;
		}
		ldptr = lfptr->lfdirptr;
		if (lfptr->lfpos > ldptr->ld_size) {
			signal(lfptr->lfmutex);
			kprintf("attempt to skip bytes beyond current end of the file\r\n");
			nxtbyte = SYSERR;
		}
		if (lfptr->lfbyte >= &lfptr->lfdblock[LF_BLKSIZ]) {
			lfsetup(lfptr);
		}
		if (lfptr->lfpos >= ldptr->ld_size) {
			ldptr->ld_size++;
		}
		*lfptr->lfbyte++ = *buff++;
		lfptr->lfpos++;
		lfptr->lfdbdirty = TRUE;
		signal(lfptr->lfmutex);
		nxtbyte = OK;
		if (nxtbyte == SYSERR) {
			return SYSERR;
		}
		else if (nxtbyte == EOF) {
			kprintf("numwrite == %d\r\n", i);
		}
	}
	return count;
}
